package com.basic.library.utils;

import android.app.Activity;
import android.os.AsyncTask;
import android.os.Environment;

import com.basic.library.base.BaseApplication;
import com.basic.library.base.BaseConstants;
import com.basic.library.utils.toast.ToastCompat;
import com.maning.mndialoglibrary.MProgressDialog;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

public class DownLoadImageTask extends AsyncTask<String, Void, Boolean> {

    private String savePath;
    private Activity activity;

    public DownLoadImageTask(Activity activity) {
        super();
        this.activity = activity;
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        MProgressDialog.showProgress(activity, "下载中...");
    }

    @Override
    protected Boolean doInBackground(String... s) {
        String fileName = s[0].substring(s[0].lastIndexOf("/"));
        savePath = Environment.getExternalStorageDirectory() + "/" + BaseConstants.Save_RootFile + "/pic";
        File f = new File(savePath);
        if (!f.exists()) {
            f.mkdir();
        }
        savePath = savePath + fileName;
        try {
            URL url = new URL(s[0]);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            DataInputStream in = new DataInputStream(connection.getInputStream());
            DataOutputStream out = new DataOutputStream(new FileOutputStream(savePath));
            byte[] buffer = new byte[4096];
            int count = 0;
            while ((count = in.read(buffer)) > 0) {
                out.write(buffer, 0, count);
            }
            out.close();
            in.close();
            connection.disconnect();
            return true;

        } catch (Exception e) {
            return false;
        }
    }

    @Override
    protected void onPostExecute(Boolean result) {
        MProgressDialog.dismissProgress();
        super.onPostExecute(result);
        ToastCompat.show(BaseApplication.getInstance()
                .getApplicationContext(), result ?
                "图片已保存至" + Environment.getExternalStorageDirectory()
                        + "/" + BaseConstants.Save_RootFile + "/pic文件夹" : "保存失败");
        if (result)
            ImageUtils.notifySys(activity, new File(savePath));
    }

}
